package com.cdream.common.lock.autoconfig;


import com.cdream.common.lock.aspect.LockAspect;
import com.cdream.common.lock.core.*;
import com.cdream.common.lock.executor.LockExecutor;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.List;

/**
 * 分布式锁自动配置器
 *
 */
@Configuration
@EnableConfigurationProperties(LockProperties.class)
@RequiredArgsConstructor
public class LockAutoConfiguration {

    private final LockProperties properties;

    @SuppressWarnings("rawtypes")
    @Bean
    @ConditionalOnMissingBean
    public LockTemplate lockTemplate(List<LockExecutor> executors) {
        LockTemplate lockTemplate = new LockTemplate();
        lockTemplate.setProperties(properties);
        lockTemplate.setExecutors(executors);
        return lockTemplate;
    }

    @Bean
    @ConditionalOnMissingBean
    public LockKeyBuilder lockKeyBuilder(BeanFactory beanFactory) {
        return new DefaultLockKeyBuilder(beanFactory);
    }

    @Bean
    @ConditionalOnMissingBean
    public LockFailureStrategy lockFailureStrategy() {
        return new DefaultLockFailureStrategy();
    }

    @Bean
    @ConditionalOnMissingBean
    public LockAspect lockAspect(@Lazy LockTemplate lockTemplate, LockKeyBuilder lockKeyBuilder,
                                 LockFailureStrategy lockFailureStrategy){
        return new LockAspect(lockTemplate, lockKeyBuilder, lockFailureStrategy, properties);
    }

}
